package splatform.webchatbot.control;

import com.jerei.web.utils.UtilsUI;
import com.jerei.web.utils.UtilsWeb;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Created by Administrator on 2017/3/4.
 */
@Controller
@RequestMapping(value = "/admin/webchatbot")
public class BotControl {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @RequestMapping(value = "/test")
    @ResponseBody
    public String test(HttpServletRequest request) {
        return UtilsUI.tip(UtilsWeb.getIp(request));
    }

    @RequestMapping(value = "/createBot")
    @ResponseBody
    public String newBot(String uid, HttpServletRequest request) throws IOException, InterruptedException {
        String basePath = request.getSession().getServletContext().getRealPath("corpse_bot");
        Runtime.getRuntime().exec("python " + basePath + "/check_corpse.py " + uid + "");
        File f = null;
        while (true) {
            f = new File(basePath + "/temp/" + uid + ".png");
            //如果图片文件被创建
            if (f.exists()) {
                break;
            }
            Thread.sleep(1000);
        }
        return UtilsUI.ok();
    }

    @RequestMapping(value = "/list")
    public String list(Model model, Long catId, HttpServletRequest request) {
        Map<String, Object> cat = jdbcTemplate.queryForMap(" select b.folder from bot_cat a , bot_type b where a.type_id = b.id and a.id = ? ", new Object[]{catId});
        model.addAttribute("imgPath", request.getContextPath() + "/tmpbots/" + (String) cat.get("folder") + "/");
        model.addAttribute("catId", catId);
        return "/admin/webchatbot/list";
    }

    @RequestMapping(value = "/page")
    @ResponseBody
    public Object page(Long catId) {
        //查询10秒内有更新的机器人
        List<Map<String, Object>> list = jdbcTemplate.queryForList("SELECT * FROM bot WHERE cat_id = ? order by id desc", new Object[]{
                catId
        });
        return UtilsUI.datagrid(list);
    }

    @RequestMapping(value = "/close")
    @ResponseBody
    public String close(Long id, HttpServletRequest request) throws InterruptedException, IOException {
        Map<String, Object> map = jdbcTemplate.queryForMap(" select a.uuid,b.config_json,c.python_name,c.folder from bot a , bot_cat b , bot_type c where a.cat_id = b.id and b.type_id = c.id and a.id = ? ", new Object[]{id});
        String uuid = (String) map.get("uuid");
        String folder = (String) map.get("folder");
        ServletContext application = request.getSession().getServletContext();
        String jqrFolderStr = application.getRealPath("/tmpbots/" + folder + "/" + uuid);
        File jqrFolder = new File(jqrFolderStr);
        if (jqrFolder.exists()) {
            FileUtils.deleteDirectory(jqrFolder);
        }
        jdbcTemplate.update(" update bot set status = 0 , op = 'exit' where id = ? ", new Object[]{
                id
        });
        //删除
        return UtilsUI.ok();
    }

    @RequestMapping(value = "/start")
    @ResponseBody
    public String start(Long id, HttpServletRequest request) throws IOException {
        //先查看机器人是否存在
        Map<String, Object> map = jdbcTemplate.queryForMap(" select a.uuid,b.config_json,c.python_name,c.folder from bot a , bot_cat b , bot_type c where a.cat_id = b.id and b.type_id = c.id and a.id = ? ", new Object[]{id});
        String uuid = (String) map.get("uuid");
        String config_json = (String) map.get("config_json");
        String python_name = (String) map.get("python_name");
        String folder = (String) map.get("folder");
        ServletContext application = request.getSession().getServletContext();
        String jqrFolderStr = application.getRealPath("/tmpbots/" + folder + "/" + uuid);
        File jqrFolder = new File(jqrFolderStr);
        //如果机器人存在,删除
        if (jqrFolder.exists()) {
            FileUtils.deleteDirectory(jqrFolder);
        }
        //重新创建病拷贝
        jqrFolder.mkdirs();
        FileUtils.copyDirectory(new File(application.getRealPath("/bots/" + folder)), jqrFolder);
        //更新配置文件
        File configFile = new File(application.getRealPath("/bots/" + folder + "/img/config.conf"));
        FileUtils.writeStringToFile(configFile, config_json, "utf-8");
        String cmd = "python " + jqrFolderStr + File.separator + python_name + ".py " + uuid;
        //调用命令行启动
        Runtime.getRuntime().exec(cmd);
        //修改状态为待扫描
        jdbcTemplate.update("update bot set last_heartbeat = NULL , status = 2 where id = ? ", new Object[]{id});
        return UtilsUI.ok();
    }

    @RequestMapping(value = "/save")
    @ResponseBody
    public String save(final Long catId) {
        final String uuid = UUID.randomUUID().toString();
        KeyHolder keyHolder = new GeneratedKeyHolder();
        final String sql = "insert into bot (uuid,cat_id) values (?,?)";
        jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement ps = connection.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
                ps.setObject(1, uuid);
                ps.setObject(2, catId);
                return ps;
            }
        }, keyHolder);
        Long id = keyHolder.getKey().longValue();
        Map<String, Object> map = jdbcTemplate.queryForMap(" select * from bot_cat where id = ? ", new Object[]{catId});
        String name = (String) map.get("name");
        name = name + "_" + id;
        jdbcTemplate.update(" update bot set name = ? where id = ? ", new Object[]{
                name, id
        });
        return UtilsUI.ok();
    }

}
